﻿using System;
using System.Collections.Generic;
using System.Linq;
using Galaktika.BI.Runtime.Services;
using Galaktika.BI.Silverlight.Services;
using Galaktika.BI.Silverlight.ClientApp.Web.Runtime;
using Galaktika.BI.Silverlight.ClientApp.Web.Runtime.DataAccess;
using Galaktika.BI.Extensibility.Dom.Dac;
using Galaktika.BI.Silverlight.Controls.DateChoice.ClientServer;
using Galaktika.BI.Silverlight.ClientApp.Web.Commands.MemberChoice;
using Ranet.Olap.Core.Data;
using Ranet.Olap.Core;

namespace Galaktika.BI.Silverlight.ClientApp.Web.Commands.DateChoice
{
    public class DateChoiceCommand : Galaktika.BI.Silverlight.Commands.ServerCommand
    {
        public DateChoiceCommand(InvokeSchema invoker)
            : base(Galaktika.BI.Silverlight.Commands.CommandId.DateChoiceCommandId)
        {
            this.ContextId = invoker[KnownInvokeArgs.ContextId];
            this.ConnectionId = invoker[KnownInvokeArgs.ConnectionId];
            this.Args = invoker[KnownInvokeArgs.DateChoiceQueryInfo];
        }

        public string ContextId { get; private set; }
        public string ConnectionId { get; private set; }
        public string Args { get; private set; }

        private IBindingContext Context
        {
            get
            {
                return DataBinder.Current.GetContext(this.ContextId);
            }
        }

        public override InvokeResultSchema Invoke()
        {
            DateChoiceQueryArgs args = XmlUtility.XmlStr2Obj<DateChoiceQueryArgs>(this.Args);
            return GetDays(args);
        }

        InvokeResultSchema GetDays(DateChoiceQueryArgs args)
        {
            var exe = (IExecutionContext)this.Context.Services.GetService(typeof(IExecutionContext));
            if (exe != null)
            {
                string connStr = null;
                BrickConnection conn = DataBinder.Current.GetNamedObject(this.ConnectionId) as BrickConnection;
                if (conn != null)
                {
                    connStr = exe.Parse(this.Context, conn.ConnectionString);
                    InvokeResultSchema res = new InvokeResultSchema(base.Id);
                    OlapProvider provider = new OlapProvider(new MDXQueryExecuter(new ConnectionInfo(connStr, connStr), Context), Context);

                    List<MemberDataWrapper> members = new List<MemberDataWrapper>();

                    foreach (String monthUniqueName in args.MonthUniqueNames)
                    {
                        members.AddRange(provider.GetChildrenMembers(args.CubeName, monthUniqueName));
                    }

                    res.ContentType = KnownContentTypes.MultidimData;
                    res.Content = XmlUtility.Obj2XmlStr(members, Common.Namespace);

                    return res;
                }
            }

            return InvokeResultSchema.Empty;
        }
    }
}
